/*
 * v1.0.1_base 
 * 修复按钮事件重复bug,
 * 新增属性: 添加msg提示框和tips
 *		time:false,//显示时间
 *		fixed:true,//是否移动
 *		offset:"auto",//位置
 * 使用说明:
 * window.wxc.tips(popHtml [, options]);
 * window.wxc.msg(popHtml [, options]);
 * window.wxc.xcConfirm(popHtml, [type], [options]);
 * popHtml:html字符串
 * type:window.wxc.xcConfirm.typeEnum集合中的元素
 * options:扩展对象
 * 用法:
 * 1. window.wxc.xcConfirm("我是弹窗<span>lalala</span>");
 * 2. window.wxc.xcConfirm("成功","success");
 * 3. window.wxc.xcConfirm("请输入","input",{onOk:function(){}})
 * 4. window.wxc.xcConfirm("自定义",{title:"自定义"})
 */
(function($){
	window.wxc = window.wxc || {};
	window.pop = window.pop || {};
	
	//window.wxc.tips("test测试","#test_5",{});
	window.wxc.tips=function(content,follow,options){
		var $box = $("<div>").addClass("xcConfirm");//弹窗插件容器
		var $layer_tips = $("<div>").addClass("msg_layer poplayer-tips ");//遮罩层 tips容器
		var $tips_content=$("<div>").addClass("poplayer-content").html(content);//文本
		var $tips_i=$("<i>").addClass("poplayer-TipsG poplayer-TipsR");//小三角
		$.extend(wxc.config,options);
		var config=$.extend({
				//hover:false, //默认关闭鼠标悬停显示;开启后,禁用显示时间.
				time: 3000,
				maxWidth: 210,
				tips: 2
			}, options);
		var time = config.time;
		var hover = config.hover;
		var popId = creatPopId();//弹窗索引
		(function init(){
//			if(!hover){
//				if(isNotNull(time)){
//					try {
//						setTimeout(doClose,time);//计时器
//					} catch(e){ setTimeout(doClose,3000) }
//				}
//			}else{
//				doHover(follow);
//			}
			if(isNotNull(time)){
					try {
						setTimeout(doClose,time);//计时器
					} catch(e){ setTimeout(doClose,3000) }
				}
			creatDom();			
		})();
		//鼠标悬停事件
		function doHover(follow){
			$(follow).hover(function(){
				creatDom();
				doLocate();
			},function(){
				doClose();
			});
		}
		//创建dom
		function creatDom(){
			$tips_content.append($tips_i);
			$layer_tips.append($tips_content);
			$box.attr("id", popId).append($layer_tips);
			$("body").append($box);
			//$layer_tips.css("margin-left",0-(($layer_tips.width())/2)+"px");
			//$layer_tips.css("margin-top",0-(($layer_tips.height())/2)+"px");
			//console.log($layer_tips.height()/2);
		}
		//关闭事件
		function doClose(){
			$("#" + popId).remove();
			$(window).unbind("keydown");
			return false;
		}
		
		//获取jq对象
		var $follow = $(follow);
		var layArea = [$layer_tips.outerWidth(), $layer_tips.outerHeight()];
		var goal = {
			width: $follow.outerWidth(),
			height: $follow.outerHeight(),
			top: $follow.offset().top,
			left: $follow.offset().left
		}, tipsG = $layer_tips.find('.poplayer-TipsG');
		  
		config.tips = typeof config.tips === 'object' ? config.tips : [config.tips, true];
		var guide = config.tips[0];
		config.tips[1] || tipsG.remove();
		  
		goal.autoLeft = function(){
			if(goal.left + layArea[0] - $(window).width() > 0){
				goal.tipLeft = goal.left + goal.width - layArea[0];
				tipsG.css({right: 12, left: 'auto'});
			} else {
				goal.tipLeft = goal.left;
			};
		};
		//辨别tips的方位
		goal.where = [function(){ //上 		
			goal.autoLeft();
			goal.tipTop = goal.top - layArea[1] - 10;
			tipsG.removeClass('poplayer-TipsR').addClass('poplayer-TipsT').css('border-right-color', config.tips[1]);
		}, function(){ //右
			goal.tipLeft = goal.left + goal.width + 10;
			goal.tipTop = goal.top;
			tipsG.removeClass('poplayer-TipsR').addClass('poplayer-TipsR').css('border-bottom-color', config.tips[1]); 
		}, function(){ //下
			goal.autoLeft();
			goal.tipTop = goal.top + goal.height + 10;
			tipsG.removeClass('poplayer-TipsR').addClass('poplayer-TipsB').css('border-right-color', config.tips[1]);
		}, function(){ //左
			goal.tipLeft = goal.left - layArea[0] - 10;
			goal.tipTop = goal.top;
			tipsG.removeClass('poplayer-TipsR').addClass('poplayer-TipsL').css('border-bottom-color', config.tips[1]);
		}];
		doLocate();
		//设置小三角的位置
		function doLocate(){
			goal.where[guide-1]();
		  
			// 8*2为小三角形占据的空间,空间不够时在反方向打开.
			if(guide === 1){
				goal.top - ($(window).scrollTop() + layArea[1] + 8*2) < 0 && goal.where[2]();
			} else if(guide === 2){
				$(window).width() - (goal.left + goal.width + layArea[0] + 8*2) > 0 || goal.where[3]()
			  } else if(guide === 3){
				(goal.top - $(window).scrollTop() + goal.height + layArea[1] + 8*2) - $(window).height() > 0 && goal.where[0]();
			} else if(guide === 4){
				layArea[0] + 8*2 - goal.left > 0 && goal.where[1]()
			}
			
			$layer_tips.find('.poplayer-content').css({
				'background-color': config.tips[1], 
				'padding-right': (config.closeBtn ? '30px' : '')
			});
			$layer_tips.css({
				left: goal.tipLeft - (config.fixed ? $(window).scrollLeft() : 0), 
				top: goal.tipTop  - (config.fixed ? $(window).scrollTop() : 0)
			});
		}
		
		
	}
	
	
	window.pop.msg=function(content, options){
		window.wxc.msg(content, options);
	}
	window.wxc.msg=function(content, options){
		debugger
		var $box = $("<div>").addClass("xcConfirm");//弹窗插件容器
		var $layer = $("<div>").addClass("msg_layer");//遮罩层
		var $txt = $("<div >").addClass("poplayer-msg").html(content);//弹窗文本dom
		$.extend(wxc.config,options)
		var config=$.extend(true,{
			//属性
			time: 3000,
//			fixed:true,//移动
//			offset:"auto", //位置
			//事件
			onClose: $.noop//弹窗关闭的回调,返回触发事件
		},options);
		var time = config.time;
		var popId = creatPopId();//弹窗索引
		(function init(){
			if(isNotNull(time)){
				try {
					setT=imeout(doClose,time);//计时器
				} catch(e){ setTimeout(doClose,3000) }
			}
//			if(config.fixed){
//				$layer.attr("onmouseover","this.style.cursor='move'");
//				wxc.drag($layer);
//			}
//			wxc.offset($layer);
			creatDom();
		})();
		//创建dom
		function creatDom(){
			$layer.append($txt);
			$box.attr("id", popId).append($layer);
			$("body").append($box);
			$layer.css("margin-left",0-(($layer.width())/2)+"px");
			$layer.css("margin-top",0-(($layer.height())/2)+"px");
			console.log($layer.height()/2);
		}
		//关闭事件
		function doClose(){
			$("#" + popId).remove();
			$(window).unbind("keydown");
			return false;
		}
	}
	window.pop.alert=function(popHtml, type, options){
		window.wxc.xcConfirm(popHtml, type, options);
	}
	window.wxc.xcConfirm = function(popHtml, type, options) {
	    var btnType = window.wxc.xcConfirm.btnEnum;
		var eventType = window.wxc.xcConfirm.eventEnum;
		var popType = {
			info: {
				title: "温馨提示",
				icon: "0 0",//蓝色i
				btn: btnType.okcancel //btnType.ok
			},
			success: {
				title: "温馨提示",
				icon: "0 -48px",//绿色对勾
				btn: btnType.ok
			},
			error: {
				title:  "温馨提示",
				icon: "-48px -48px",//红色叉
				btn: btnType.ok
			},
			confirm: {
				title: "温馨提示",
				icon: "-48px 0",//黄色问号
				btn: btnType.okcancel
			},
			warning: {
				title: "温馨提示",
				icon: "0 -96px",//黄色叹号
				btn: btnType.okcancel
			},
			input: {
				title: "温馨提示",
				icon: "",
				btn: btnType.okcancel
			},
			custom: {
				title: "",
				icon: "",
				btn: btnType.ok
			}
		}; 
		var itype = type ? type instanceof Object ? type : popType[type] || {} : {};//格式化输入的参数:弹窗类型
		$.extend(wxc.config,options);
		var config = $.extend(true, {
			//属性
			title: "", //自定义的标题
			icon: "", //图标
			time:false,//显示时间
			fixed:true,//是否移动
			offset:"auto",//位置
			btn: btnType.ok, //按钮,默认单按钮
			//事件
			onOk: $.noop,//点击确定的按钮回调
			onCancel: $.noop,//点击取消的按钮回调
			onClose: $.noop//弹窗关闭的回调,返回触发事件
		}, itype, options);
		
		var $txt = $("<div style='width:auto;'></div>").html(popHtml);//弹窗文本dom
		var $tt = $("<span>").addClass("tt").text(config.title);//标题
		var icon = config.icon;
		var $icon = icon ? $("<div style='float:left;'>").addClass("bigIcon").css("backgroundPosition",icon) : "";
		var btn = config.btn;//按钮组生成参数
		var time = config.time;
		var popId = creatPopId();//弹窗索引
	    
		var $box = $("<div>").addClass("xcConfirm").addClass("uncopy");//弹窗插件容器
		var $layer = $("<div>").addClass("xc_layer");//遮罩层
		var $popBox = $("<div>").addClass("popBox");//弹窗盒子
		var $ttBox = $("<div>").addClass("ttBox");//弹窗顶部区域
		var $txtBox = $("<div>").addClass("txtBox");//弹窗内容主体区
		var $btnArea = $("<div>").addClass("btnArea");//按钮区域
		var $ok = $("<a>").addClass("sgBtn").addClass("ok").text("确定");//确定按钮
		var $cancel = $("<a>").addClass("sgBtn").addClass("cancel").text("取消");//取消按钮 
		var $input = $("<input>").addClass("inputBox");//输入框
		var $clsBtn = $("<a>").addClass("clsBtn");//关闭按钮
		
		//建立按钮映射关系
		var btns = {
			ok: $ok,
			cancel: $cancel
		};
		init();
		function init(){
			//$(".xcConfirm").remove(); 
			//处理特殊类型input
			if(popType["input"] === itype){
				$txt.append($input);
			}
			if(isNotNull(time)){
				try {
					setTimeout(doClose,time);//计时器
				} catch(e){ setTimeout(doClose,3000) }
			}
			creatDom();
			wxc.offset($popBox);
			
			bind();
			if(config.fixed){
				$ttBox.attr("onmouseover","this.style.cursor='move'");
				wxc.drag($popBox);
			}
		}
		
		function creatDom(){
			$popBox.append(
				$ttBox.append(
					$clsBtn
				).append(
					$tt
				)
			).append(
				$txtBox.append($icon).append($txt)
			).append(
				$btnArea.append(creatBtnGroup(btn))
			);
			$box.attr("id", popId).append($layer).append($popBox);
			$("body").append($box);
		}
		
		function bind(){
			//点击确认按钮
			$ok.click(doOk);

			//回车键触发确认按钮事件
			$(window).bind("keydown", function(e){
				if(e.keyCode == 13) {
					if($("#" + popId).length == 1){
						doOk();
					}
				}
			});
			
			//点击取消按钮
			$cancel.click(doCancel);
			
			//点击关闭按钮
			$clsBtn.click(doClose);
		}

		//确认按钮事件
		function doOk(){
			var $o = $(this);
			var v = $.trim($input.val());
			if ($input.is(":visible"))
		        config.onOk(v);
		    else
		        config.onOk();
			$("#" + popId).remove(); 
			 
			config.onClose(eventType.ok);
			
	        return true; 
		}
		
		//取消按钮事件
		function doCancel(){
			var $o = $(this);
			config.onCancel();
			$("#" + popId).remove(); 
			config.onClose(eventType.cancel);
			return false;
		}
		
		//关闭按钮事件
		function doClose(){
			$("#" + popId).remove();
			config.onClose(eventType.close);
			$(window).unbind("keydown");
			return false;
		}
		
		//生成按钮组
		function creatBtnGroup(tp){
			var $bgp = $("<div>").addClass("btnGroup");
			$.each(btns, function(i, n){
				if( btnType[i] == (tp & btnType[i]) ){
					$bgp.append(n);
				}
			});
			return $bgp;
		}

	};
	//重生popId,防止id重复
	function creatPopId(){
		var i = "pop_" + (new Date()).getTime()+parseInt(Math.random()*100000);//弹窗索引
		if($("#" + i).length > 0){
			return creatPopId();
		}else{
			return i;
		}
	}
	function isNotNull(str){
		return typeof (str) != 'undefined' && str != null&& str != ""
	}
	//拖拽
	window.wxc.drag=function(obj){
		var objtt=obj.children("div.ttBox");
		if(objtt.length>0){
			objtt.bind("mousedown",start);
		}else{
			obj.bind("mousedown",start);
		}
        
        function start(event){
            if(event.button==0){//判断是否点击鼠标左键
                
//                  pageX和pageY代表鼠标当前的横纵坐标
//                  position()该方法返回的对象包含两个整型属性：top 和 left，以像素计。此方法只对可见元素有效。
//                  bind()绑定事件，同样unbind解绑定，此效果的实现最后必须要解绑定，否则鼠标松开后拖拽效果依然存在
//                  getX获取当前鼠标横坐标和对象离屏幕左侧距离之差（也就是left）值，
//                  getY和getX同样道理，这两个差值就是鼠标相对于对象的定位，因为拖拽后鼠标和拖拽对象的相对位置是不变的
                 
                gapX=event.pageX-obj.position().left;
                gapY=event.pageY-obj.position().top;
                //movemove事件必须绑定到$(document)上，鼠标移动是在整个屏幕上的
                $(document).bind("mousemove",move);
                //此处的$(document)可以改为obj
                $(document).bind("mouseup",stop);
               
            }
            return false;//阻止默认事件或冒泡
        }
        function move(event){
			var X=event.pageX-gapX,
				Y=event.pageY-gapY;
			//防止拖动到屏幕外
			X<285&&(X=285);
			X>($(window).width()-obj.width()+285) && (X=$(window).width()-obj.width()+285);
			Y<150&&(Y=150);
			Y>($(window).height()-obj.height()+150) && (Y=$(window).height()-obj.height()+150);
			
        	obj.css({
                "left":X+"px",
                "top":Y+"px"
            });
            return false;//阻止默认事件或冒泡
        }
        function stop(){
            //解绑定，这一步很必要，前面有解释
            $(document).unbind("mousemove",move);
            $(document).unbind("mouseup",stop);
            
        }
    }
	//默认配置
	window.wxc.config={
		time:false,//显示时间
		fixed:true,//是否移动
		offset:"auto",//位置
	}
	//计算坐标
	window.wxc.offset = function(obj){
		var w=obj.width();
		var h=obj.height();
		var that = this, config = that.config;
		//var area = [obj.position().left, obj.position().top];
		var area = [obj.width(), obj.height()];
		var type = typeof config.offset === 'object';
		that.offsetTop = ($(window).height() - area[1])/2+150;
		that.offsetLeft = ($(window).width() - area[0])/2+285;
		if(type){
			that.offsetLeft = config.offset[0]+285;
			that.offsetTop = config.offset[1]+150||that.offsetLeft;
		} else if(config.offset !== 'auto'){
			if(config.offset === 't'){ //上
				that.offsetTop = 150;
			} else if(config.offset === 'r'){ //右
				that.offsetLeft = $(window).width() - area[0]+285;
			} else if(config.offset === 'b'){ //下
				that.offsetTop = $(window).height() - area[1]+150;
			} else if(config.offset === 'l'){ //左
				that.offsetLeft = 285;
			} else if(config.offset === 'lt'){ //左上角
				that.offsetTop = 150;
				that.offsetLeft = 285;
			} else if(config.offset === 'lb'){ //左下角
				that.offsetTop = $(window).height() - area[1]+150;
				that.offsetLeft = 285;
			} else if(config.offset === 'rt'){ //右上角
				that.offsetTop = 150;
				that.offsetLeft = $(window).width() - area[0]+285;
			} else if(config.offset === 'rb'){ //右下角
				that.offsetTop = $(window).height() - area[1]+150;
				that.offsetLeft = $(window).width() - area[0]+285;
			} else {
				that.offsetTop = config.offset;
			}
    
		}
		obj.css({top: that.offsetTop, left: that.offsetLeft});
	};
	
	//按钮类型
	window.wxc.xcConfirm.btnEnum = {
		ok: parseInt("0001",2), //确定按钮
		cancel: parseInt("0010",2), //取消按钮
		okcancel: parseInt("0011",2) //确定&&取消
	};
	
	//触发事件类型
	window.wxc.xcConfirm.eventEnum = {
		ok: 1,
		cancel: 2,
		close: 3
	};
	
	//弹窗类型
	window.wxc.xcConfirm.typeEnum = {
		info: "info",
		success: "success",
		error:"error",
		confirm: "confirm",
		warning: "warning",
		input: "input",
		custom: "custom"
	};

})(jQuery);